/*
* Copyright 2011 Lauri Nevala.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.fitness;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import calculator.Calculator;

import database.dbCreation;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;


public class PersonalRecord_CalendarView extends Activity implements OnClickListener{

	public Calendar month;
	public CalendarAdapter adapter;
	public Handler handler;
	public ArrayList<String> items; // container to store some random calendar items
	TextView selected_date;
	TextView day_report;
	TextView hint;
	Button menu_btn1;
    Button menu_btn2;
	//Button menu_btn3;
	Intent nextActivity;
	String s_month;
	String s_year;
	 dbCreation.DbHelper db = new dbCreation.DbHelper(this);
	 final Context cur_context = this;
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.calendar);
	    
		menu_btn1 = (Button)findViewById(R.id.menu_btn1);
		menu_btn2 = (Button)findViewById(R.id.menu_btn2);
		//menu_btn3 = (Button)findViewById(R.id.menu_btn3);
		menu_btn1.setOnClickListener(this);
		menu_btn2.setOnClickListener(this);
		//menu_btn3.setOnClickListener(this);
		menu_btn1.setText("Calorie Calculator");
		//menu_btn2.setText("Health Chart");
		menu_btn2.setText("Analysis");
	    
	    selected_date = (TextView)findViewById(R.id.selected_date);
        day_report = (TextView)findViewById(R.id.day_report);
        hint = (TextView)findViewById(R.id.hint);
        
	    month = Calendar.getInstance();
	    
	    items = new ArrayList<String>();
	    adapter = new CalendarAdapter(this, month);
	    
	    GridView gridview = (GridView) findViewById(R.id.gridview);
	    gridview.setAdapter(adapter);
	    
	    //mark date cells that have records, do databse query in calendarUpdater run()
	    handler = new Handler();
	    handler.post(calendarUpdater);
	    
	    TextView title  = (TextView) findViewById(R.id.title);
	    title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
	    
	    TextView previous  = (TextView) findViewById(R.id.previous);
	    previous.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(month.get(Calendar.MONTH)== month.getActualMinimum(Calendar.MONTH)) {				
					month.set((month.get(Calendar.YEAR)-1),month.getActualMaximum(Calendar.MONTH),1);
				} else {
					month.set(Calendar.MONTH,month.get(Calendar.MONTH)-1);
				}
				System.out.println("current month: "+month.get(Calendar.MONTH));
				refreshCalendar();
			}
		});
	    
	    TextView next  = (TextView) findViewById(R.id.next);
	    next.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(month.get(Calendar.MONTH)== month.getActualMaximum(Calendar.MONTH)) {				
					month.set((month.get(Calendar.YEAR)+1),month.getActualMinimum(Calendar.MONTH),1);
				} else {
					month.set(Calendar.MONTH,month.get(Calendar.MONTH)+1);
				}
				System.out.println("current month: "+month.get(Calendar.MONTH));
				refreshCalendar();
				
			}
		});
	    
		gridview.setOnItemClickListener(new OnItemClickListener() {
		    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		    	TextView date = (TextView)v.findViewById(R.id.date);
		        if(date instanceof TextView && !date.getText().equals("")) {
		        	
		        	//Intent intent = new Intent();
		        	String day = date.getText().toString();
		        	if(day.length()==1) {
		        		day = "0"+day;
		        	}
		        	//System.out.println(android.text.format.DateFormat.format("yyyy-MM", month)+"-"+day);
		        	String result = "";
		        	HashMap<String, Double> foodmap = db.foodByDate(s_year, s_month, day);
		        	//go through hashmap for food
		        	Iterator iter_Food = foodmap.entrySet().iterator();
		        	while(iter_Food.hasNext())
		        	{
		        		Map.Entry me = (Map.Entry)iter_Food.next();
		        		String foodname = me.getKey().toString();
		        		String quantity = me.getValue().toString();
		        		String unit = db.getunit(foodname);
		        		
		        		result += foodname+":  "+quantity+unit+"\r\n"; 
		        	}
		        	
		        	HashMap<String, Integer> actmap = db.activityByDate(s_year, s_month, day);
		        	Iterator iter_Act = actmap.entrySet().iterator();
		         	while(iter_Act.hasNext())
		        	{
		        		Map.Entry me = (Map.Entry)iter_Act.next();
		        		String actname = me.getKey().toString();
		        		String quantity = me.getValue().toString();
		        		
		        		
		        		result += actname+":  "+quantity+"Hours"+"\r\n"; 
		        	}
		         Calculator calculator = new Calculator(cur_context);
		        	double takein = calculator.foodIntake_Calc(foodmap);
		        	double burn = -(double)calculator.activity_Calc(actmap);
		        	result += "Total takein Calorie:"+Double.toString(takein+burn);
		        	String selected_date_string = android.text.format.DateFormat.format("yyyy-MM", month)+"-"+day;
			           //display selected date
			        selected_date.setText(selected_date_string);
			           //pull report of the selected date from database, such as meal details, calorie, weight, etc.
			        day_report.setMovementMethod(new ScrollingMovementMethod());
			        day_report.setText(result);
			        
			        //v.setSelected(true);
			        
			        //v.setBackgroundColor(Color.parseColor("#FF99CC"));
			           //Toast.makeText(getApplicationContext(), selected_date_string, Toast.LENGTH_SHORT).show();
		        	// return chosen date as string format 
//		        	intent.putExtra("date", android.text.format.DateFormat.format("yyyy-MM", month)+"-"+day);
//		        	setResult(RESULT_OK, intent);
//		        	finish();
		        }
		        
		    }
		});
	}
	
	public void refreshCalendar()
	{
		TextView title  = (TextView) findViewById(R.id.title);
		
		adapter.refreshDays();
		adapter.notifyDataSetChanged();				
		handler.post(calendarUpdater); 			
		
		title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));
	}
	
	public Runnable calendarUpdater = new Runnable() {
		
		@Override
		public void run() {
			items.clear();
			//use current calendar month to run a query, and grab and mark all events
			//date string can be reformatted
			//extracts the "date"(string, no leading zero), and add to items arraylist, then setItems will be called.
			//System.out.println("update: "+android.text.format.DateFormat.format("MM-yyyy", month));
            String show_Year = Integer.toString(month.get(Calendar.YEAR));
            String show_Month = Integer.toString(month.get(Calendar.MONTH)+1);
            
            s_year = show_Year;
            s_month = show_Month;
            System.out.println("year ="+show_Year+"; Month ="+show_Month);
            
            List<String> RecordList = db.monthRecord(show_Year, show_Month);
			//e.g. 3,7,9 will be marked in every month
			//items.add("3");
			//items.add("7");
			//items.add("9");
            items = new ArrayList(RecordList);
			adapter.setItems(items);
			adapter.notifyDataSetChanged();
		}
	};

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
        case R.id.menu_btn1:
        	nextActivity = new Intent(PersonalRecord_CalendarView.this, CalcTab.class);
        	startActivity(nextActivity);
            break;
        case R.id.menu_btn2:
        	nextActivity = new Intent(PersonalRecord_CalendarView.this, AnalTab.class);
        	startActivity(nextActivity); 
            break;
//        case R.id.menu_btn3:
//        	nextActivity = new Intent(PersonalRecord_CalendarView.this, AnalysisReportActivity.class);
//        	startActivity(nextActivity);
//            break; 
        default:
            break;
        }		
	}
}
